<?php

/**
 * @name        : Fpt_Caching_Page
 * @version     : 20120315
 * @copyright   : FOSP
 * @todo        : Caching Entire Page 
 * @author      : QuangTM
 */
class Fpt_Caching_Page
{

    /**
     * Fpt_Caching_Page's instance
     * @var Fpt_Caching_Page
     */
    protected static $instance;

    protected function __construct()
    {
        
    }

    /**
     * Get Fpt_Caching_Page's instance
     * @return Fpt_Caching_Page
     */
    public static function getInstance()
    {
        if (!isset(self::$instance) || !self::$instance instanceof self)
            self::$instance = new self;
        return self::$instance;
    }

    /**
     * Get caching file path
     * @param array $options 
     * $options = array(
     *      'url' => string,
     *      'baseUrl' => string,
     *      'cacheDir' => string,
     * )
     * @param string $pathFile
     * @access protected
     * @return string
     */
    protected function getPath($options, &$pathFile)
    {       
        // Get and trim slash char from arguments
        $script_path = $options['cacheDir'].rtrim($options['url'], '/');
        if(strrpos($script_path, '.html'))
        {
            $pathFile = $script_path;
            $script_path = dirname($script_path);
        }
        else
        {
            $pathFile = $script_path.'/index.html';
        }
        return $script_path;
    }
    /**
     * Remove empty folder
     * @param string $dir 
     * @access protected
     */
    protected function removeDir($dir)
    {
        $numberFile = count(scandir($dir));
        if ($numberFile == 2)
        {
            $parentDir = dirname($dir);
            rmdir($dir);
            $this->removeDir($parentDir);
        }
    }
    
    /**
     * Cache entire page to html file
     * @param array $options
     * $options = array(
     *      'url' => string,
     *      'baseUrl' => string,
     *      'cacheDir' => string,
     *      'content' => string
     * )
     * @return bool
     */
    public function write($options)
    {
        try
        {
            $pathFile = '';
            // Get caching path to store cache html file
            $path = $this->getPath($options, $pathFile);
            // Check path is exist or not
            if (file_exists($path))
            {
                if (!is_dir($path))
                    if (APP_ENV == 'development')
                        throw new Exception("This path: \"$path\" is not a directory");
                    else
                        return FALSE;
                else if (!is_writable($path))
                    if (APP_ENV == 'development')
                        throw new Exception("This directory \"$path\" is not writable folder");
                    else
                        return FALSE;
                else
                {
                    // Put content to file html
                    file_put_contents($pathFile, $options['content']);
                }
            }
            else
            {
                // Create folder first
                mkdir($path, 0750, TRUE);

                // Put content to file html
                file_put_contents($pathFile, $options['content']);
            }

            return TRUE;
        }
        catch (Exception $ex)
        {
            Fpt_Log::sendlog(4, $ex->getCode(), $ex->getMessage(), $ex->getTraceAsString(), null, null);
            return FALSE;
        }
    }

    /**
     * Get content from caching page to string
     * @param array $options 
     * $options = array(
     *      'url' => string,
     *      'baseUrl' => string,
     *      'cacheDir' => string,
     * )
     * @return string|bool
     */
    public function read($options)
    {
        $pathFile = '';
        // Get path to cache file html
        $path = $this->getPath($options, $pathFile);
        
        if (file_exists($pathFile))
            return file_get_contents ($pathFile);
        else
            if (APP_ENV == 'development')
                throw new Exception("This file \"$pathFile\" is not exist!");
            else
                return FALSE;
    }
    
    /**
     * Delete cache file
     * @param array $options 
     * $options = array(
     *      'url' => string,
     *      'baseUrl' => string,
     *      'cacheDir' => string,
     * )
     * @return bool
     */
    public function delete($options)
    {
        $pathFile = '';
        // Get path to cache file html
        $path = $this->getPath($options, $pathFile);
        if(file_exists($pathFile))
            unlink ($pathFile);
        $this->removeDir($path);
        return TRUE;
    }

}